import json
import urllib
from http.server import BaseHTTPRequestHandler, HTTPServer
import dashscope
import os
from openai import OpenAI
from http import HTTPStatus
from dashscope import Application
import json
import types
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.hunyuan.v20230901 import hunyuan_client, models

os.environ['DASHSCOPE_API_KEY'] = 'sk-5be701ab68ee425d9da64875321b576c'
dashscope.api_key = 'sk-5be701ab68ee425d9da64875321b576c'
os.environ['HUNYUAN_API_KEY'] = 'sk-USN8WOjJqZ6PvlMcd1smBmmoI2R8g2B0WTU18BSvntxdAxCP'
ali_agent_app_id = 'e45019ebd83b4ef08755c16f36d4c358'
tencent_secretid = 'AKID8QmHvsxHarHxcRF1j3UzTqAe8TuOtHcq'
tencent_secretkey = 'MsTldVTdpwunYEAzqfdUWXXYl9fM8qjp'


def call_ali_agent_app(prompttext):
    print('prompttext:', prompttext)
    response = Application.call(app_id=ali_agent_app_id,
                                prompt=prompttext,
                                api_key=dashscope.api_key,
                                # 如果在开始节点定义了变量，请在这里传参
                                # biz_params = {
                                #    "city": "杭州",
                                #    "date": "明天"
                                # }
                                )
    print('agent:', response)
    return response


def call_ali_audio(user, audio, prompttext):
    print('user:', user)
    print('audio:', audio)
    print('prompttext:', prompttext)
    msg = [
        {
            "role": user,
            "content": [
                {"audio": audio},
                {"text": prompttext}
            ]
        }
    ]
    response = dashscope.MultiModalConversation.call(
        model="qwen2-audio-instruct",
        messages=msg,
        result_format="message"
    )
    print(response)
    return response


def call_hunyuan_role(user, prompttext):
    print('hunyuan-role')
    print('user:', user)
    print('prompttext:', prompttext)
    # 构造 client
    client = OpenAI(
        api_key=os.environ.get("HUNYUAN_API_KEY"),  # 混元 APIKey
        base_url="https://api.hunyuan.cloud.tencent.com/v1",  # 混元 endpoint
    )

    completion = client.chat.completions.create(
        model="hunyuan-role",
        messages=[
            {
                "role": user,
                "content": prompttext,
            },
        ],
        extra_body={
            "enable_enhancement": True,  # <- 自定义参数
        },
    )
    print(completion)
    return completion


def call_hunyuan_image(user, base64content, prompttext):
    print('call_hunyuan_image')
    print('user:', user)
    # 构造 client
    # 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
    # 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议采用更安全的方式来使用密钥，请参见：https://cloud.tencent.com/document/product/1278/85305
    # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
    cred = credential.Credential(tencent_secretid, tencent_secretkey)
    # 实例化一个http选项，可选的，没有特殊需求可以跳过
    httpProfile = HttpProfile()
    httpProfile.endpoint = "hunyuan.tencentcloudapi.com"

    # 实例化一个client选项，可选的，没有特殊需求可以跳过
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    # 实例化要请求产品的client对象,clientProfile是可选的
    client = hunyuan_client.HunyuanClient(cred, "", clientProfile)

    # 实例化一个请求对象,每个接口都会对应一个request对象
    req = models.ChatCompletionsRequest()
    params = {
        "Model": "hunyuan-vision",
        "Messages": [
            {
                "Role": "user",
                "Contents": [
                    {
                        "Type": "text",
                        "Text": prompttext
                    },
                    {
                        "Type": "image_url",
                        "ImageUrl": {
                            "Url": base64content
                        }
                    },
                ]
            }
        ],
        "Stream": False
    }
    req.from_json_string(json.dumps(params))

    # 返回的resp是一个ChatCompletionsResponse的实例，与请求对象对应
    resp = client.ChatCompletions(req)
    # 输出json格式的字符串回包
    print(resp)
    return resp


class handler(BaseHTTPRequestHandler):
    def do_GET(self):
        print('get request received', self.path)
        if self.path == '/api/voice-recognition':
            message = call_ali_audio('user', 'https://competition-1255792859.cos.ap-guangzhou.myqcloud.com/test.aac',
                                     '直接说出音频内容')
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()

            print('audio:', message)
            message = call_hunyuan_role('user', '你是谁？' + message.output.choices[0].message.content[0]['text'])
            self.wfile.write(bytes(str(message.choices[0].message.content), "utf8"))
            return
        elif self.path == '/api/agent-app':
            message = call_ali_agent_app('参加此次比赛，需要用到哪些开发工具')
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(bytes(str(message), "utf8"))
        else:
            print('invalid path ', self.path)
            self.send_response(404)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            self.wfile.write(bytes(str('无效地址'), "gbk"))
            return

    def do_POST(self):
        print('post request received')
        try:
            if self.path == '/api/agent-app':
                return self.call_agent_app()
            elif self.path == '/api/voice-recognition':
                return self.call_voice_role()
            elif self.path == '/api/image-recognition':
                return self.call_image_role()
            else:
                print('invalid path ', self.path)
                self.send_response(404)
                self.send_header('Content-type', 'text/html')
                self.end_headers()
                self.wfile.write(bytes(str('无效地址'), "utf8"))
                return
        except Exception as e:
            print(repr(e))
            self.send_response(500)
            self.send_header('Content-type', 'text/html')
            self.end_headers()

            self.wfile.write(bytes(repr(e), "gbk"))

    def call_agent_app(self):
        content_length = int(self.headers.get('Content-Length'))
        post_data = self.rfile.read(content_length)
        params = urllib.parse.parse_qs(post_data.decode('utf-8'))

        message = call_ali_agent_app(params['prompttext'][0])
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(bytes(str(message), "utf8"))

    def call_voice_role(self):
        content_length = int(self.headers.get('Content-Length'))
        post_data = self.rfile.read(content_length)
        params = urllib.parse.parse_qs(post_data.decode('utf-8'))

        message = call_ali_audio(params['userrole'][0], params['base64'][0], '直接说出音频内容')

        audio = message.output.choices[0].message.content[0]['text']
        print('audio:', audio)
        message = call_hunyuan_role(params['userrole'][0], params['prompttext'][0] + '。 主人说：' + audio)

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(bytes(str(message.choices[0].message.content), "utf8"))

    def call_image_role(self):
        content_length = int(self.headers.get('Content-Length'))
        post_data = self.rfile.read(content_length)
        params = urllib.parse.parse_qs(post_data.decode('utf-8'))
        message = call_hunyuan_image(params['userrole'][0],
                                     'data:image/jpeg;base64,' + params['base64'][0],
                                     "下边图中人脸是什么情绪？只能选择其中一种，情绪种类有：愤怒、高兴、忧郁、生气、呲牙、做鬼脸")

        image_content = message.Choices[0].Message.Content
        print('image_content:', image_content)
        message = call_hunyuan_role(params['userrole'][0],
                                    params['prompttext'][0] + '。 主人现在的情绪是：' + image_content)
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(bytes(str(message.choices[0].message.content), "utf8"))


with HTTPServer(('', 3200), handler) as server:
    server.serve_forever()
